package com.alks.function.service.impl;

import com.alks.common.aop.AutoPageAop;
import com.alks.common.aop.RedisLock;
import com.alks.common.data.dto.SysUserTokenDTO;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.service.RedisService;
import com.alks.common.utils.DateUtils;
import com.alks.common.utils.excelUtils.ExcelUtils;
import com.alks.common.utils.stringUtils.ZStringUtils;
import com.alks.entity.data.entity.*;
import com.alks.entity.data.entity.imes.*;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.SdBomPartNew2Rep;
import com.alks.function.data.dto.chengKong.assort.YfBomPartNew2Dto;
import com.alks.function.data.request.quotation.PcStyleCraftRequest;
import com.alks.function.data.request.quotation.bom.BomDataCopyReq;
import com.alks.function.data.request.quotation.bom.BusinessMtlReq;
import com.alks.function.data.request.stock.SdMtlNewReq;
import com.alks.function.mapper.MaterialMapper;
import com.alks.function.mapper.SdStyleMapper;
import com.alks.function.mapper.SdUserMapper;
import com.alks.function.service.SdStyleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.support.atomic.RedisAtomicInteger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @author:hxl
 * @create: 2024-01-10 11:23
 * @Description:
 */
@Service
@Slf4j
public class SdStyleServiceImpl implements SdStyleService {

    @Autowired
    private SdStyleMapper sdStyleMapper;

    @Override
    @AutoPageAop
    public ResponseInfo getUnProcessStyle(PcStyleCraftRequest rep, String choose) throws InterruptedException {
        rep.setCompanyId(UserIdThread.get().getCompanyId());
        Map<String, Object> map = new HashMap<>();
        List<PcStyleCraftRep> list = null;
        Page<PcStyleCraftRep> page = null;
        if ("1".equals(choose)) {
            list = sdStyleMapper.getUnProcessStyle(rep);
            page = (Page<PcStyleCraftRep>) list;
        } else if ("2".equals(choose)) {
            list = sdStyleMapper.getSelectStyle(rep);
            page = (Page<PcStyleCraftRep>) list;
        } else if ("3".equals(choose)) {
            list = sdStyleMapper.getProcessHead(rep);
            page = (Page<PcStyleCraftRep>) list;
        } else {
            list = sdStyleMapper.getReturnSelect(rep);
            page = (Page<PcStyleCraftRep>) list;
        }
        map.put("list", list);
        map.put("total", page.getTotal());
        return ResponseInfo.ok(map);
    }

    @Override
    @Transactional
    public ResponseInfo insertProcess(PcStyleCraftRequest rep) {
        rep.setCompanyId(UserIdThread.get().getCompanyId());
        List<PcStyleCraftRep> selectStyle = sdStyleMapper.getSelectStyle(rep);
        if (!selectStyle.isEmpty()) {
            return ResponseInfo.error("型体已检核");
        }
        sdStyleMapper.insertProcess(rep, UserIdThread.get());
        List<StyleProductionProcess> list = sdStyleMapper.getSdBomPartNew2(rep);
        HashSet<String> strings = new HashSet<>();
        List<StyleProductionProcess> collect = list.stream().filter(new Predicate<StyleProductionProcess>() {
            @Override
            public boolean test(StyleProductionProcess styleProductionProcess) {
                if (!strings.contains(styleProductionProcess.getPartName())) {
                    strings.add(styleProductionProcess.getPartName());
                    return true;
                }
                return false;
            }
        }).collect(Collectors.toList());
        collect.sort(Comparator.comparing(StyleProductionProcess::getSeqNo));
        int i = 1;
        for (StyleProductionProcess process : collect) {
            process.setSeqNo(new BigDecimal(i));
            i++;
        }
        sdStyleMapper.deleteAllProcessDetail(rep);
        if (!collect.isEmpty()) {
            sdStyleMapper.insertProcessNew(collect, rep);
        } else {
            throw new ServiceErrorException("未找到生产资料");
        }
        return ResponseInfo.ok("取资料成功");
    }

    @Override
    public ResponseInfo getStyleProductionList(PcStyleCraftRequest request, String flag) {
        request.setCompanyId(UserIdThread.get().getCompanyId());
        List<StyleProductionProcess> list = sdStyleMapper.getStyleProductionList(request);
        if ("1".equals(flag)) {
            list = list.stream().filter(x -> {
                if (ZStringUtils.noeNotNullProcess(x)) {
                    return true;
                }
                return false;
            }).collect(Collectors.toList());
        }
        return ResponseInfo.ok(list);
    }

    @Override
    @Transactional
    public ResponseInfo copyStyleProcess(String style1, String style2, String color1, String color2) {
        PcStyleCraftRequest request1 = new PcStyleCraftRequest();
        request1.setStyle(style1);
        request1.setColor(color1);
        PcStyleCraftRequest request2 = new PcStyleCraftRequest();
        request2.setStyle(style2);
        request2.setColor(color2);
        request1.setCompanyId(UserIdThread.get().getCompanyId());
        request2.setCompanyId(UserIdThread.get().getCompanyId());
//        sdStyleMapper.deleteAllProcessDetail(request2);
//        sdStyleMapper.insertIntoSdProcess(request1,request2);
        List<StyleProductionProcess> list1 = sdStyleMapper.getStyleProductionList(request1);
        List<StyleProductionProcess> list2 = sdStyleMapper.getStyleProductionList(request2);
        List<StyleProductionProcess> collect = list1.stream().filter(styleProductionProcess -> {
            for (StyleProductionProcess process : list2) {
                if (process.getPartName().equals(styleProductionProcess.getPartName())) {
                    return true;
                }
            }
            return false;
        }).collect(Collectors.toList());
        if (!collect.isEmpty()) sdStyleMapper.copyStyleProcess(collect, request2);
        return ResponseInfo.ok();
    }

    @Autowired
    RedisService redisService;

    @Override
    @Transactional
    public ResponseInfo creatCutAndProcess(PcStyleCraftRequest req, String choose) {
        req.setCompanyId(UserIdThread.get().getCompanyId());
        String flag = sdStyleMapper.getFlagByProcessHead(req.getStyle(),req.getColor(),UserIdThread.get().getCompanyId());
        if ("Y".equals(flag)) throw new ServiceErrorException("该型体检核");
        List<StyleProductionProcess> list = sdStyleMapper.getStyleProductionList(req);
        list.forEach(x -> x.setCompanyId(UserIdThread.get().getCompanyId()));
        String[] strings = {"SF", "码", "张", "Y", "米"};
        List<String> stringList = Arrays.asList(strings);
        if ("1".equals(choose)) {
            List<StyleProductionProcess> collect = list.stream().filter(x -> stringList.contains(x.getMtlUnit())).collect(Collectors.toList());
            for (StyleProductionProcess styleProductionProcess : collect) {
                String name = sdStyleMapper.getTypeName("STK", UserIdThread.get().getCompanyId(), 1);
                String process = sdStyleMapper.getprocess1("101", "01", UserIdThread.get().getCompanyId());
                styleProductionProcess.setProcess1(process);
                styleProductionProcess.setStkFlag(name);
            }
            if (ZStringUtils.isEmpty(collect)) return ResponseInfo.ok("生成成功");
            sdStyleMapper.insertLog(collect, req);
            sdStyleMapper.updateCut(collect, req);
        } else {
            List<StyleProductionProcess> collect = list.stream().filter(x -> x.getProcess1() != null && !"".equals(x.getProcess1())).collect(Collectors.toList());
            if (ZStringUtils.isEmpty(collect)) return ResponseInfo.ok("生成成功");
            sdStyleMapper.insertLog(collect, req);
            sdStyleMapper.updateProcess(collect, req);
        }
        return ResponseInfo.ok();
    }

    @Override
    @Transactional
    public ResponseInfo optionStyleProcess(StyleProductionProcess req, String choose, String style, String styleColor) {
        String flag = sdStyleMapper.getFlagByProcessHead(style,styleColor,UserIdThread.get().getCompanyId());
        if ("Y".equals(flag)) throw new ServiceErrorException("该型体检核");
        String option = "";
        SysUserTokenDTO dto = UserIdThread.get();
        req.setCompanyId(dto.getCompanyId());
        Integer num = sdStyleMapper.getCheckNum(style, styleColor);
        if (num > 0) throw new ServiceErrorException("该型体已检核");
        if (req.getCutSeq() != null) {
            switch (req.getCutSeq()) {
                case "一裁":
                case "CẮT 1":
                    req.setCutSeq("1");
                    break;
                case "二裁":
                case "CẮT 2":
                    req.setCutSeq("2");
                    break;
                case "三裁":
                case "CẮT 3":
                    req.setCutSeq("3");
                    break;
                case "四裁":
                case "CẮT 4":
                    req.setCutSeq("4");
                    break;
                default:
                    req.setCutSeq("");
                    break;
            }
        }
        if (req.getStkFlag() != null) {
            switch (req.getStkFlag()) {
                case "冲裁配套仓":
                case "KHO PHỐI ĐÔI CẮT CHẶT":
                    req.setStkFlag("1");
                    break;
                case "面底配套仓":
                case "KHO PHỐI ĐÔI MẶT ĐẾ":
                    req.setStkFlag("2");
                    break;
                default:
                    req.setStkFlag("");
                    break;
            }
        }
        switch (choose) {
            case "1":
                option = "INSERT";
                sdStyleMapper.insertIntoProcess(req, style, styleColor);
                break;
            case "2":
                option = "DELETE";
                sdStyleMapper.deleteIntoProcess(req, style, styleColor);
                //查询 sd_bom_style_new2 删除存在里面的数据需要添加进 PC_DIFF_PART
                //判断该部位是否存在 存在则不添加 不存在添加
                Integer count = sdStyleMapper.getCount(req, style, styleColor);
                Integer diffNum = sdStyleMapper.getDiffCount(req, style, styleColor);
                diffNum = diffNum == null ? 0 : diffNum;
                if (count != null && count > 0 && diffNum <= 0)
                    sdStyleMapper.insertIntoPcDiffPart(req, style, styleColor, dto);
                break;
            case "3":
                option = "UPDATE";
                sdStyleMapper.updateStyleProcess(req, style, styleColor);
                break;
        }
        req.setStyle(style);
        sdStyleMapper.insertIntoLogs(req, option, dto);
        return ResponseInfo.ok();
    }

    @Override
    public ResponseInfo renewalSiteDifferenceList(String style, String color) {
        List<PcDiffPart> list = sdStyleMapper.renewalSiteDifferenceList(UserIdThread.get(), style, color);
        return ResponseInfo.ok(list);
    }

    @Override
    @Transactional
    public ResponseInfo renewalSiteDifference(List<PcDiffPart> req, String choose) {
        String name = UserIdThread.get().getLoginName();
        if ("1".equals(choose)) {
            for (PcDiffPart diffPart : req) {
                String flag = sdStyleMapper.getFlagByProcessHead(diffPart.getStyle(),diffPart.getStyleColor(),UserIdThread.get().getCompanyId());
                if ("Y".equals(flag)) throw new ServiceErrorException("该型体检核");
                diffPart.setCompanyId(UserIdThread.get().getCompanyId());
                sdStyleMapper.deleteSize(diffPart, name);
                List<StyleProductionProcess> list = sdStyleMapper.getSeq(diffPart);
                List<StyleProductionProcess> collect = list.stream().filter(x -> x.getSeqNo().intValue() == (diffPart.getSeqNo().intValue()) && x.getPartName().equals(diffPart.getPartName())).collect(Collectors.toList());
                List<StyleProductionProcess> partNames = list.stream().filter(x -> x.getPartName().equals(diffPart.getPartName())).collect(Collectors.toList());
                if (ZStringUtils.isEmpty(collect)) {
                    BigDecimal add = sdStyleMapper.getMaxSeq(diffPart).add(new BigDecimal("1"));
                    diffPart.setSeqNo(add);
                }
                if (!ZStringUtils.isEmpty(partNames)) {
                    sdStyleMapper.updateSdProcess(diffPart);
                } else sdStyleMapper.insertIntoSdStylePro(diffPart);
            }

        } else {
            for (PcDiffPart diffPart : req) {
                sdStyleMapper.deleteSize(diffPart, name);
            }
        }
        return ResponseInfo.ok();
    }

    @Override
    public ResponseInfo processUpdateRecord(String style, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Map<String, Object> map = new HashMap<>();
        List<SdStyleProcessNewLog> list = sdStyleMapper.processUpdateRecord(style, UserIdThread.get().getCompanyId());
        Page<SdStyleProcessNewLog> page = (Page<SdStyleProcessNewLog>) list;
        map.put("list", list);
        map.put("total", page.getTotal());
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo returnCutDeptList() {
        Map<String, Object> map = new HashMap<>();
        List<String> cuts = sdStyleMapper.getLs("CUT", UserIdThread.get().getCompanyId());
        List<String> depts = sdStyleMapper.getLs("STK", UserIdThread.get().getCompanyId());
        List<String> process = sdStyleMapper.getProcess();
        map.put("cuts", cuts);
        map.put("depts", depts);
        map.put("process", process);
        return ResponseInfo.ok(map);
    }

    @Override
    @Transactional
    public ResponseInfo checkProcessRecord(List<PcStyleCraftRequest> req, String check) {
        if (ZStringUtils.isEmpty(req)) {
            return ResponseInfo.error("不能传入空数据");
        }
        int count = 0;
        for (PcStyleCraftRequest request : req) {
            request.setCompanyId(UserIdThread.get().getCompanyId());
            if ("1".equals(check)) {
                //有工艺没裁次 有裁次没裁层
                int cut = 0;
                int cutLayer = 0;
                int cutNum = 0;
                List<String> list1 = Arrays.asList("冲裁", "切割", "dao chặt", "cắt tự động");
                List<StyleProductionProcess> list = sdStyleMapper.getStyleProductionList(request);
                for (StyleProductionProcess process : list) {
                    if (process.getCutSeq() != null & list1.contains(process.getProcess1()) & process.getCutLayer() == null) {
                        cutLayer++;
                    }
                    if (process.getCutNum() != null) {
                        cutNum++;
                    }
                    if (ZStringUtils.noeNotNullProcess(process)) {
                        if (process.getCutSeq() == null || process.getCutSeq().isEmpty()) {
                            cut++;
                        }
                    }
                }
                if (cutLayer > 0) {
                    return ResponseInfo.error(request.getStyle() + "有0个裁层记录");
                }
                if (cutNum <= 0) {
                    return ResponseInfo.error(request.getStyle() + "有0个每双片数个记录");
                }
//                if (cut > 0) {
//                    return ResponseInfo.error("型体" + request.getStyle() + "有" + cut + "个有工艺没裁次的记录");
//                }
                StyleProductionProcess productionProcess = list.stream().max(Comparator.comparing(StyleProductionProcess::getSeqNo)).get();
                int seqNo = productionProcess.getSeqNo().intValue();
                for (StyleProductionProcess process : list) {
                    List<String> processList = ZStringUtils.getProcess(process);
                    for (String string : processList) {
                        seqNo++;
                        String partName = process.getPartName() + "(" + string + ")";
                        List<StyleProductionProcess> collect = list.stream().filter(x -> x.getPartName().equals(partName)).collect(Collectors.toList());
                        if (!collect.isEmpty()) {
                            continue;
                        }
                        StyleProductionProcess newProcess = getNewProcess(process, partName, seqNo);
                        sdStyleMapper.insertIntoProcess(newProcess, process.getStyle(), process.getColor());
                    }
                }
                sdStyleMapper.updateCheck(request, "Y");
            } else {
                Integer counts = sdStyleMapper.getDispatchByStyle(request);
                sdStyleMapper.updateCheck(request, "");
                if (counts > 0) {
                    count++;
                }
            }
        }
        List<String> list = List.of("FCL","LTF");
        if (count > 0 && !list.contains(UserIdThread.get().getUserId())) {
            throw  new ServiceErrorException("存在已派工的记录，请先联系范科长取消检核");
        }
        return ResponseInfo.ok("修改成功");
    }

    @NotNull
    private static StyleProductionProcess getNewProcess(StyleProductionProcess process, String partName, Integer seqNo) {
        StyleProductionProcess newProcess = new StyleProductionProcess();
        newProcess.setPartName(partName);
        newProcess.setCompanyId(process.getCompanyId());
        newProcess.setMtlName(process.getMtlName());
        newProcess.setMtlSpec(process.getMtlSpec());
        newProcess.setMtlUnit(process.getMtlUnit());
        newProcess.setCutLayer(process.getCutLayer());
        newProcess.setCutNum(process.getCutNum());
        String cutSeq = process.getCutSeq() == null ? "" : process.getCutSeq();
        switch (cutSeq) {
            case "一裁":
            case "CẮT 1":
                newProcess.setCutSeq("1");
                break;
            case "二裁":
            case "CẮT 2":
                newProcess.setCutSeq("2");
                break;
            case "三裁":
            case "CẮT 3":
                newProcess.setCutSeq("3");
                break;
            case "四裁":
            case "CẮT 4":
                newProcess.setCutSeq("4");
                break;
            default:
                newProcess.setCutSeq("");
                break;
        }
        String stkFlag = process.getStkFlag() == null ? "" : process.getStkFlag();
        switch (stkFlag) {
            case "冲裁配套仓":
            case "KHO PHỐI ĐÔI CẮT CHẶT":
                newProcess.setStkFlag("1");
                break;
            case "面底配套仓":
            case "KHO PHỐI ĐÔI MẶT ĐẾ":
                newProcess.setStkFlag("2");
                break;
            default:
                newProcess.setStkFlag("");
        }
        newProcess.setCutNum2(process.getCutNum2());
        newProcess.setProcess1(process.getProcess1());
        newProcess.setSeqNo(BigDecimal.valueOf(seqNo));
        return newProcess;
    }

    @Override
    @AutoPageAop
    public ResponseInfo getSdBomFitSubNew2(YfBomPartNew2Dto req) {
        return ResponseInfo.ok(sdStyleMapper.getSdBomFitSubNew2(req));
    }

    @Override
    @Transactional
    public ResponseInfo laminatedWoodDecomposition(List<YfBomPartNew2Dto> list) {
        for (YfBomPartNew2Dto subNew2 : list) {
            List<SdBomFitSubNew2> new2s = sdStyleMapper.getSdBomFitSubNew2(subNew2);
            if (new2s != null || !new2s.isEmpty()) {
                sdStyleMapper.deleteSdBomFitSub(subNew2);
            }
            List<SdBomFitSubNew2> subs = new ArrayList<>();
            if (subNew2.getMtlTypeNo().contains("N") || subNew2.getMtlName().contains("+") || subNew2.getMtlNo().contains("N")) {
                String mtlColor = subNew2.getMtlColor();
                String mtlName = subNew2.getMtlName();
                String[] names = mtlName.split("\\+");
                String[] colors = mtlColor.split("\\+");
                for (int i = 0; i < names.length; i++) {
                    SdBomFitSubNew2 new2 = getSdBomFitSubNew2(names, i, colors);
                    subs.add(new2);
                }
            }
            subNew2.setCompanyId(UserIdThread.get().getCompanyId());
            //添加数据库
            sdStyleMapper.addTypeChildren(subNew2, subs);
        }
        return ResponseInfo.ok("分解完成");
    }

    @NotNull
    private static SdBomFitSubNew2 getSdBomFitSubNew2(String[] names, int i, String[] colors) {
        String name = names[i];
        SdBomFitSubNew2 new2 = new SdBomFitSubNew2();
        new2.setMtlName(name);
        if (colors.length > i) {
            new2.setMtlColor(colors[i]);
            new2.setMtlSeq(BigDecimal.valueOf(i + 1));
        } else {
            String c = name.substring(0, name.indexOf("色") + 1);
            String n = name.substring(name.indexOf("色") + 1);
            new2.setMtlName(n);
            new2.setMtlColor(c);
            new2.setMtlSeq(BigDecimal.valueOf(i + 1));
        }
        return new2;
    }

    @Override
    @Transactional
    public ResponseInfo fitSplitConfirmation(SdBomFitSubNewReq req) {
        List<SdBomFitSubNew2> list = req.getList();
        List<SdBomFitSubNew2> collect = list.stream().filter(x -> x.getSubMtlTypeNo() == null || x.getSubMtlTypeNo().isEmpty()).collect(Collectors.toList());
        if (!collect.isEmpty()) {
            return ResponseInfo.error("请先填入分类名称");
        }
        String name = UserIdThread.get().getUserName();
        SdBomFitSubNew2 subNew2 = new SdBomFitSubNew2();
        subNew2.setSubMtlName(req.getMtlName());
        subNew2.setSubMtlColor(req.getMtlColor());
        subNew2.setSubMtlUnit(req.getMtlUnit());
        subNew2.setSubMtlSpec(req.getMtlSpec());
        String subNew2MtlNo = sdStyleMapper.getMtlNoByName(subNew2);
        if (subNew2MtlNo == null || subNew2MtlNo.isEmpty()) {
            SdBomFitSub sub = new SdBomFitSub();
            sub.setSubMtlColor(req.getMtlColor());
            //根据序号修改数据库SD_BOM_PART_NEW2
            Integer subNew2Max = sdStyleMapper.getMaxByTypeNo(req.getMtlTypeNo());
            subNew2Max++;
            subNew2MtlNo = String.format(req.getMtlTypeNo() + "%05d", subNew2Max);
            SdBomFitSubNew2 new2 = new SdBomFitSubNew2();
            new2.setSubMtlNo(subNew2MtlNo);
            new2.setSubMtlColor(req.getMtlColor());
            new2.setSubMtlName(req.getMtlName());
            new2.setSubMtlSpec(req.getMtlSpec());
            new2.setSubMtlUnit(req.getMtlUnit());
            new2.setCompanyId(UserIdThread.get().getCompanyId());
            sdStyleMapper.insertSdBomMtl(new2, name);
        }
        //将数据写入SD_BOM_PART_NEW2
        sdStyleMapper.updateSdBomPartNew2(req, subNew2MtlNo);
        //如果当前材料不存在的话需要在 SD_BOM_FIT_SUB 修改SD_BOM_FIT_SUB_NEW2 添加SD_BOM_MTL 添加SD_MTL_NEW 添加SD_MTL_SUB_NEW
        for (SdBomFitSubNew2 new2 : list) {
            String typeNo = new2.getSubMtlTypeNo();
            if (typeNo == null || typeNo.isEmpty()) {
                return ResponseInfo.error("分类名称未填");
            }
            String mtlNo = sdStyleMapper.getMtlNoByName(new2);
            String subMtlNo1 = sdStyleMapper.getMtlNo1(new2);
            new2.setSubMtlNo1(subMtlNo1);
            new2.setSubMtlNo(mtlNo);
            if (subMtlNo1 == null || subMtlNo1.isEmpty()) {
                Integer maxNo1 = sdStyleMapper.getFromSdMtlNew(typeNo);
                maxNo1++;
                subMtlNo1 = String.format(typeNo + "%05d", maxNo1);
                new2.setSubMtlNo1(subMtlNo1);
                new2.setCompanyId(UserIdThread.get().getCompanyId());
                sdStyleMapper.insertSdMtlNew(new2, name);
            }
            if (mtlNo == null || mtlNo.isEmpty()) {
                //生成新的mtlNo 添加进SD_MTL_NEW
                Integer maxNo2 = sdStyleMapper.getMaxByTypeNo(typeNo);
                maxNo2++;
                mtlNo = String.format(subMtlNo1 + "%04d", maxNo2);
                new2.setSubMtlNo(mtlNo);
                new2.setCompanyId(UserIdThread.get().getCompanyId());
                sdStyleMapper.insertSdBomMtl(new2, name);

            }
            //查询 SD_MTL_SUB_NEW SD_BOM_FIT_SUB 根据subMtlName 和 mtlName 查询不存在添加
            new2.setMtlName(req.getMtlName());
            new2.setMtlColor(req.getMtlColor());
            new2.setMtlUnit(req.getMtlUnit());
            new2.setMtlSpec(req.getMtlSpec());
            String sdMtlSubNewNo = sdStyleMapper.getFromSdMtlSubNew(new2);
            if (sdMtlSubNewNo == null || sdMtlSubNewNo.isEmpty()) {
                new2.setMtlNo(subNew2MtlNo.substring(0, 9));
                new2.setCompanyId(UserIdThread.get().getCompanyId());
                sdStyleMapper.insertInToSdMtlSubNew(req, new2, name);
            }
            String sdBomFitSubNo = sdStyleMapper.getFromSdFitSubNo(new2);
            if (sdBomFitSubNo == null || sdBomFitSubNo.isEmpty()) {
                new2.setMtlNo(subNew2MtlNo);
                new2.setCompanyId(UserIdThread.get().getCompanyId());
                sdStyleMapper.insertIntoFitSub(req, new2, name);
            }
            sdStyleMapper.updateFitSplitConfirmation(new2);
        }
        return ResponseInfo.ok();
    }

    @Override
    @Transactional
    public ResponseInfo sectionalSectionFiling(YfBomPartNew2Dto req, Integer segment) {
        if (segment <= 1) {
            return ResponseInfo.error("分段数不正确");
        }
        if (Integer.parseInt(req.getSegment()) >= 1) {
            log.info(req.getSegment());
            return ResponseInfo.error("非0分段");
        }
        String no = req.getSeqNo();
        int seg = Integer.parseInt(req.getSeqNo()) + segment - 1;
        req.setSeqNo(String.valueOf(seg));
        sdStyleMapper.updatePartSeq(req);
        for (Integer i = 1; i < segment; i++) {
            int seq = Integer.parseInt(no) + i;
            req.setSeqNo(String.valueOf(seq));
            req.setSegment(String.valueOf(i));
            sdStyleMapper.insertIntoBomPart(req);
            sdStyleMapper.insertBatchNew2(req);
        }
        return ResponseInfo.ok("分段完成");
    }

    @Override
    @Transactional
    public ResponseInfo generateMaterialCode(List<YfBomPartNew2Dto> list) {
        String name = UserIdThread.get().getUserName();
        for (YfBomPartNew2Dto dto : list) {
            if (dto.getMtlName() == null) {
                return ResponseInfo.error("物料名称不能为空");
            }
            if (dto.getMtlTypeNo() == null || dto.getTypeName() == null) {
                return ResponseInfo.error("请先进行分类辅助生成");
            }
        }
        List<YfBomPartNew2Dto> collect = list.stream().filter(x -> {
            if (x.getMtlName().contains("+") || "合贴".equals(x.getTypeName()) || x.getMtlTypeNo().contains("N")) {
                if (x.getMtlNo() == null || x.getMtlNo().isEmpty()) {
                    return true;
                }
            }
            return false;
        }).collect(Collectors.toList());
        if (!collect.isEmpty()) {
            return ResponseInfo.error("贴合材料请先处理");
        }
        HashMap<String, Integer> map = new HashMap<>();
        List<YfBomPartNew2Dto> collect1 = list.stream().filter(x -> x.getMtlNo() == null || x.getMtlNo().isEmpty()).collect(Collectors.toList());
        for (YfBomPartNew2Dto dto : collect1) {
            //查询是否含有该物料编码在sdbommtl中
            SdBomFitSubNew2 sdBom = new SdBomFitSubNew2();
            sdBom.setSubMtlName(dto.getMtlName());
            sdBom.setSubMtlColor(dto.getMtlColor());
            sdBom.setSubMtlUnit(dto.getMtlUnit());
            sdBom.setSubMtlSpec(dto.getMtlSpec());
            String mtlNo = sdStyleMapper.getMtlNoByName(sdBom);
            SdBomFitSub sub = new SdBomFitSub();
            sub.setSubMtlColor(dto.getMtlColor());
            String mtlColor = dto.getMtlColor();
            if (mtlNo == null || mtlNo.isEmpty()) {
                String newMtlNo = sdStyleMapper.getMtlNo1(sdBom);
                String colorCode = sdStyleMapper.getColorCode(sub);
                String newColorCode = hueColor(colorCode, name, mtlColor);
                if (newMtlNo == null || newMtlNo.isEmpty()) {
                    if (dto.getMtlTypeNo() == null || dto.getMtlTypeNo().isEmpty()) {
                        return ResponseInfo.ok("检查参数");
                    }
                    Set<String> set = map.keySet();
                    boolean b = set.contains(dto.getMtlTypeNo());
                    Integer max = 0;
                    if (!b) {
                        max = sdStyleMapper.getFromSdMtlNew(dto.getMtlTypeNo());
                        if (max == null) max = 0;
                    } else {
                        max = map.get(dto.getMtlTypeNo());
                    }
                    max++;
                    map.put(dto.getMtlTypeNo(), max);
                    newMtlNo = String.format(dto.getMtlTypeNo() + "%05d", max);
                    sdBom.setSubMtlNo1(newMtlNo);
                    sdStyleMapper.insertSdMtlNew(sdBom, name);
                    //添加材料到SDMTLNEW
                }
                mtlNo = newMtlNo + newColorCode;
                sdBom.setSubMtlNo(mtlNo);
                sdBom.setCompanyId(UserIdThread.get().getCompanyId());
                sdStyleMapper.insertSdBomMtl(sdBom, name);
                dto.setMtlNo(newMtlNo);
            }
            dto.setMtlNo(mtlNo);
        }
        if (!collect1.isEmpty()) {
            sdStyleMapper.updateSdBomPartNew2List(collect1);
        }
        return ResponseInfo.ok("物料编码生成完成");
    }

    private String hueColor(String colorCode, String name, String mtlColor) {
        if (colorCode == null || colorCode.isEmpty()) {
            Integer max = sdStyleMapper.getMaxColor();
            PcMtlHueDesignRep rep = new PcMtlHueDesignRep();
            max += 1;
            String format = String.format("%04d", max);
            rep.setColorCode(format);
            rep.setColorName("全色系");
            materialMapper.insertColorDesign(rep, name, mtlColor);
            return format;
        }
        return colorCode;
    }

    @Override
    public ResponseInfo updateFitSplitConfirmation(SdBomFitSubNew2 req) {
        sdStyleMapper.updateFitSplitConfirmation(req);
        return ResponseInfo.ok();
    }

    @Override
    public ResponseInfo setNullMaterialCode(YfBomPartNew2Dto req) {
        sdStyleMapper.setNullMaterial(req);
        return ResponseInfo.ok();
    }

    @Override
    public ResponseInfo createTypeNo(List<YfBomPartNew2Dto> req) {
        for (YfBomPartNew2Dto dto : req) {
            if (dto.getMtlName() == null || dto.getMtlName().isEmpty()) {
                continue;
            }
            if (dto.getMtlName().contains("+")) {
                dto.setMtlTypeNo("N301");
            } else {
                dto.setCompanyId(UserIdThread.get().getCompanyId());
                String mtlNo = sdStyleMapper.getBySdBomMtl(dto);
                if (mtlNo == null) {
                    return null;
                }
                if (mtlNo.contains("N")) {
                    dto.setMtlTypeNo("N301");
                } else {
                    dto.setMtlTypeNo(mtlNo.substring(0, 4));
                }
            }
        }
        sdStyleMapper.updateSdBomPartNew2List(req);
        return ResponseInfo.ok();
    }

    @Override
    public ResponseInfo classificationKeyList(SdMtlTypeKey req) {
        return ResponseInfo.ok(sdStyleMapper.classificationKeyList(req));
    }

    @Override
    public ResponseInfo addClassificationKey(SdMtlTypeKey req) {
        req.setCompanyId(UserIdThread.get().getCompanyId());
        sdStyleMapper.insertIntoKey(req);
        return ResponseInfo.ok();
    }

    @Override
    @Transactional
    public ResponseInfo bomDataReplication(BomDataCopyReq req) {
        sdStyleMapper.bomDataReplication(req);
        return ResponseInfo.ok();
    }

    @Override
    public ResponseInfo generateBMtl(BusinessMtlReq req) {
        SdBomFitSubNew2 new2 = new SdBomFitSubNew2();
        new2.setSubMtlName(req.getMtlName());
        new2.setSubMtlColor(req.getMtlColor());
        new2.setSubMtlSpec(req.getMtlSpec());
        new2.setSubMtlUnit(req.getMtlUnit());
        new2.setSubMtlNo(req.getMtlNo() + req.getColorCode());
        String mtlNoByName = sdStyleMapper.getMtlNoByName(new2);
        if (mtlNoByName != null && !mtlNoByName.isEmpty()) {
            return ResponseInfo.error("该业务材料已存在");
        }
        new2.setCompanyId(UserIdThread.get().getCompanyId());
        sdStyleMapper.insertSdBomMtl(new2, UserIdThread.get().getUserName());
        return ResponseInfo.ok();
    }

    @Override
    public ResponseInfo getSdMtlSubNew(String mtlNo) {
        return ResponseInfo.ok(sdStyleMapper.getSdMtlSubNew(mtlNo));
    }

    @Override
    @AutoPageAop
    public ResponseInfo getSdBomMtl(SdMtlNewReq req) {
        Map<String, Object> map = new HashMap<>();
        List<SdMtlNew> list = sdStyleMapper.getSdBomMtl(req);
        Page<SdMtlNew> page = (Page<SdMtlNew>) list;
        map.put("list", list);
        map.put("total", page.getTotal());
        return ResponseInfo.ok(map);
    }

    @Autowired
    private MaterialMapper materialMapper;

    @Override
    @Transactional
    public ResponseInfo subFitOption(List<SdBomFitSub> list) {
        String name = UserIdThread.get().getUserName();
        for (SdBomFitSub sdBomFitSub : list) {
            String colorCode = "0000";
            if (sdBomFitSub.getSubMtlColor() != null) {
                colorCode = sdStyleMapper.getColorCode(sdBomFitSub);
            }
            if (colorCode == null || colorCode.isEmpty()) {
                Integer max = sdStyleMapper.getMaxColor();
                PcMtlHueDesignRep rep = new PcMtlHueDesignRep();
                max += 1;
                String format = String.format("%4d", max);
                rep.setColorCode(format);
                rep.setColorName("全色系");
                materialMapper.insertColorDesign(rep, name, sdBomFitSub.getSubMtlColor());
            }
            SdBomFitSubNew2 new2 = new SdBomFitSubNew2();
            new2.setSubMtlName(sdBomFitSub.getSubMtlName());
            new2.setSubMtlSpec(sdBomFitSub.getSubMtlSpec());
            new2.setSubMtlUnit(sdBomFitSub.getSubMtlUnit());
            new2.setSubMtlColor(sdBomFitSub.getSubMtlColor());
            String mtlNo = sdBomFitSub.getSubMtlNo();
            new2.setSubMtlNo(mtlNo + colorCode);
            String mtlNoByName = sdStyleMapper.getMtlNoByName(new2);
            if (mtlNoByName != null || !mtlNoByName.isEmpty()) {
                continue;
            }
            sdStyleMapper.insertSdBomMtl(new2, name);
        }
        return ResponseInfo.ok();
    }

    @Override
    @Transactional
    public ResponseInfo copyCurrTo(SdBomPartNew2Rep req) {
        sdStyleMapper.copyCurrTo(req);
        List<String> seqs = req.getSeqs();
        for (String seq : seqs) {
            sdStyleMapper.deleteBomFit(req, seq);
            sdStyleMapper.copyBomFit(req, seq);
        }
        return ResponseInfo.ok();
    }

    @Override
    public ResponseInfo getMtlColor(String colorName, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Map<String, Object> map = new HashMap<>();
        List<String> list = sdStyleMapper.getMtlColor(colorName);
        Page<String> page = (Page<String>) list;
        map.put("list", list);
        map.put("total", page.getTotal());
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo getColorWithCode(String color, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> list = sdStyleMapper.getColorWithCode(color);
        Page<Map<String, Object>> page = (Page<Map<String, Object>>) list;
        map.put("list", list);
        map.put("total", page.getTotal());
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo getSdMtlSubFit(String mtlNo) {
        return ResponseInfo.ok(sdStyleMapper.getSdMtlSubFit(mtlNo));
    }

    @Override
    public void downloadStyleProcess(HttpServletResponse response, List<PcStyleCraftRequest> list) throws IOException {
        List<StyleProductionProcess> processes = new ArrayList<>();
        for (PcStyleCraftRequest request : list) {
            processes.addAll(sdStyleMapper.getStyleProductionList(request));
        }
        for (StyleProductionProcess process : processes) {
            String stkFlag = process.getStkFlag();
            if (stkFlag != null) {
                if ("BF".equals(UserIdThread.get().getCompanyId())) process.setStkFlag(stkFlag.substring(0, stkFlag.indexOf("仓")));
                if ("HF".equals(UserIdThread.get().getCompanyId())) process.setStkFlag(process.getStkFlag());
            }
        }
        ExcelUtils.creatByTemplate(response, "型体生产工艺模板.xlsx", "型体生产工艺_" + DateUtils.dateTimeNow(), processes);
    }

    @Override
    public ResponseInfo busMtlDelete(String mtlNo) {
        materialMapper.deleteSdBomMtl(mtlNo);
        materialMapper.deleteSdBomFitSub(mtlNo);
        return ResponseInfo.ok();
    }

    @Override
    public ResponseInfo getParamSet(String type, String name, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Map<String, Object> map = new HashMap<>();
        List<ParamSettingResp> list = sdStyleMapper.getParamSet(type, name);
        Page<ParamSettingResp> page = (Page<ParamSettingResp>) list;
        map.put("list", list);
        map.put("total", page.getTotal());
        return ResponseInfo.ok(map);
    }

    @Override
    @Transactional
    public ResponseInfo optionParam(ParamSettingResp req, String choose) {
        String username = UserIdThread.get().getLoginName();
        String type = req.getType();
        switch (type) {
            case "工艺":
                type = "A";
                break;
            case "阶段":
                type = "B";
                break;
            case "问题类型":
                type = "C";
                break;
            case "订单类型":
                type = "D";
                break;
        }
        Integer i = sdStyleMapper.getMaxCode(type);
        if ("1".equals(choose)) {
            i += 1;
            String code = String.format(type + "%04d", i);
            req.setCode(code);
            req.setType(type);
            req.setCompanyId(UserIdThread.get().getCompanyId());
            sdStyleMapper.insertIntoBaseCode(req, username);
            return ResponseInfo.ok("添加成功");
        } else if ("2".equals(choose)) {
            sdStyleMapper.deleteBaseCode(req);
        }
        return ResponseInfo.ok();
    }

    @Override
    public ResponseInfo getTaskFiling(String custNo, String styleNo, String taskState, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Map<String, Object> map = new HashMap<>();
        List<TaskFillingResp> list = sdStyleMapper.getTaskFiling(custNo, styleNo, taskState);
        Page<TaskFillingResp> page = (Page<TaskFillingResp>) list;
        map.put("list", list);
        map.put("total", page.getTotal());
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo optionTask(List<TaskFillingResp> req, String choose) {
        for (TaskFillingResp resp : req) {
            if ("1".equals(resp.getTaskState())) return ResponseInfo.error("操作失败");
        }
        sdStyleMapper.optionTask(req, choose);
        return ResponseInfo.ok();
    }

    @Override
    public ResponseInfo getTaskFilingDetail(String styleNo, String styleColor) {
        Map<String, Object> map = new HashMap<>();
        List<String> sizes = sdStyleMapper.getSizes(styleNo);
        List<String> cuts = sdStyleMapper.getCuts(styleNo);
        List<String> lasts = sdStyleMapper.getLasts(styleNo);
        List<String> sole = sdStyleMapper.getSoles(styleNo);
        List<StyleSizeRowToColumn> result = new ArrayList<>();
        List<TrailTaskHead> typeList = sdStyleMapper.getTaskFilingDetail(styleNo, styleColor);
        for (int i = 0; i < typeList.size(); i++) {
            TrailTaskHead head = typeList.get(i);
            StyleSizeRowToColumn typeData = new StyleSizeRowToColumn(head.getOrderType(), head.getStageType(), head.getPlanDate(), head.getSysUser(), head.getCompanyId());
            typeData.setRedoReason(head.getRedoReason());
            typeData.setStyleNo(head.getStyleNo());
            typeData.setTaskNo(head.getTaskNo());
            typeData.setSeqNo(head.getSeqNo());
            typeData.setPrintFlag(head.getPrintFlag());
            List<StyleSize> sizeList = sdStyleMapper.selectStyleSizeByStyleYF(styleNo);
            typeData.setLastIndex(sizeList.size());
            for (int j = 0; j < sizeList.size(); j++) {
                TrailTaskSize trailTaskSize = new TrailTaskSize();
                trailTaskSize.setTaskNo(head.getTaskNo());
                trailTaskSize.setSize_no(((StyleSize) sizeList.get(j)).getSizeNo());
                trailTaskSize.setStyleNo(head.getStyleNo());
                trailTaskSize = sdStyleMapper.querytTrailTaskSize(trailTaskSize);
                if (trailTaskSize != null)
                    try {
                        Method method = typeData.getClass().getDeclaredMethod("setQty" + (j + 1), new Class[]{String.class});
                        method.invoke(typeData, new Object[]{trailTaskSize.getQty() + ""});
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
            }
            result.add(typeData);
        }
        map.put("sizes", sizes);
        map.put("cuts", cuts);
        map.put("lasts", lasts);
        map.put("sole", sole);
        map.put("list", result);
        return ResponseInfo.ok(map);
    }

    @Override
    @Transactional
    public ResponseInfo updateTaskStateQty(TaskFilingDetailResp req) {
        if ("Y".equals(req.getPrintFlag())) return ResponseInfo.error("该工艺已打印");
        req.setCompanyId(UserIdThread.get().getCompanyId());
        if ("1".equals(req.getChoose())) {
            req.setOrderType("重做");
            String compId = "BF";
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMdd");
            String ymd = dateFormat.format(new Date());
            int lastNum = 0;
            String lastTaskNo = sdStyleMapper.getLastSerialNum(compId + ymd);
            if (lastTaskNo != null) {
                lastTaskNo = lastTaskNo.substring(lastTaskNo.length() - 4, lastTaskNo.length());
                try {
                    lastNum = Integer.valueOf(lastTaskNo).intValue();
                } catch (Exception exception) {
                }
            }
            String newTaskNo = compId + ymd.substring(0, 6) + String.format("%04d", new Object[]{Integer.valueOf(lastNum + 1)});
            int res = sdStyleMapper.insertTrailProcess(req, UserIdThread.get(), newTaskNo);
            return ResponseInfo.ok(res);
        }
        //查询这个taskNo有没有数据有修改没有新增
        Integer num = sdStyleMapper.getTaskSizeQty(req);
        int i = sdStyleMapper.getTaskSizeQtys(req);
        if (i > 0) return ResponseInfo.error("该工艺已采集");
        if (num > 0) {
            sdStyleMapper.updateTaskTrailSize(req);
        } else if (!ZStringUtils.isNull(req.getQty()) && !ZStringUtils.isNull(req.getSeqNo())) {
            sdStyleMapper.insertIntoTrailSize(req);
        }
        //不能设置的qty不能少于已采集数
        BigDecimal totalQty = sdStyleMapper.getTaskSizeQtyTotal(req);
        totalQty = totalQty == null ? BigDecimal.ZERO : totalQty;
        //设置planQty
        BigDecimal planQty = sdStyleMapper.getTaskPlanQty(req);
        planQty = planQty == null ? BigDecimal.ZERO : planQty;
        if (totalQty.compareTo(planQty) < 0) throw new ServiceErrorException("不能设置的qty不能少于已采集数");
        req.setPlanQty(totalQty);
        sdStyleMapper.updateTaskHeadSize(req);
        return ResponseInfo.ok();
    }

    @Override
    public List<JiZhuanJinDuTree> treeList(JiZhuanJinDuSearchObj searchObj) {
        List<String> groupField = searchObj.getGroupField();
        if (ZStringUtils.isEmpty(groupField)) return null;
        List<Field> fields = new ArrayList<>(groupField.size());
        try {
            for (String fieldName : groupField) {
                Field field = JiZhuanJinDuTree.class.getDeclaredField(fieldName);
                field.setAccessible(true);
                fields.add(field);
            }
            List<JiZhuanJinDuTree> list = sdStyleMapper.queryJiZhuanJinDuTree(searchObj);
            List<JiZhuanJinDuTree> result = getTrees(list, groupField, fields);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalArgumentException("无效的分组字段");
        }
    }

    @Override
    @AutoPageAop
    public ResponseInfo queryHeadList(JiZhuanJinDuSearchObj searchObj) {
        Map<String, Object> map = new HashMap<>();
        List<JiZhuanJinDu> list = sdStyleMapper.queryJiZhuanJinDu(searchObj);
        map.put("list", list);
        map.put("total", new PageInfo(list).getTotal());
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo creatTask(TaskFillingResp req) {
        QcBaseParam param = new QcBaseParam();
        param.setStageFlag("Y");
        List<QcBaseParam> qcBaseParamList = sdStyleMapper.selectByExample(param);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMdd");
        String ymd = dateFormat.format(new Date());
        String compId = "BF";
        if (qcBaseParamList == null || qcBaseParamList.size() == 0) {
            return ResponseInfo.error("请先创建阶段任务!!");
        }

        List<StyleSize> sizeList = sdStyleMapper.selectStyleSizeByStyleYF(req.getStyleNo());
        if (sizeList == null || sizeList.size() == 0) {
            return ResponseInfo.error("当前型体颜色尺码数据为空,请先添加尺码数据!!");
        }
        String lastTaskNo = sdStyleMapper.getLastSerialNum(compId + ymd);
        int lastNum = 0;
        if (lastTaskNo != null) {
            lastTaskNo = lastTaskNo.substring(lastTaskNo.length() - 4, lastTaskNo.length());
            try {
                lastNum = Integer.valueOf(lastTaskNo).intValue();
            } catch (Exception exception) {
            }
        }
        for (int i = 0; i < qcBaseParamList.size(); i++) {
            TrailTaskHead trailTaskHead = new TrailTaskHead();
            trailTaskHead.setCutTool(req.getCutTool());
            trailTaskHead.setLastMold(req.getLastMold());
            trailTaskHead.setCompanyId("BF");
            trailTaskHead.setOrderType("正单");
            trailTaskHead.setTaskNo(compId + ymd.substring(0, 6) + String.format("%04d", new Object[]{Integer.valueOf(lastNum + i + 1)}));
            trailTaskHead.setPlanDate(new Date());
            trailTaskHead.setSeqNo(Integer.valueOf(i));
            trailTaskHead.setStyleNo(req.getStyleNo());
            trailTaskHead.setSolePart(req.getSolePart());
            trailTaskHead.setSoleVendor(req.getSoleVendor());
            trailTaskHead.setStyleColor(req.getStyleColor());
            trailTaskHead.setStageType(((QcBaseParam) qcBaseParamList.get(i)).getName());
            trailTaskHead.setSysDate(new Date());
            trailTaskHead.setSysUser(UserIdThread.get().getLoginName());
            sdStyleMapper.insertIntoTrail(trailTaskHead);
        }
        req.setTaskState("1");
        sdStyleMapper.updateStyleColorTaskStateYF(req);
        return ResponseInfo.ok();
    }

    @Override
    public List<JiZhuanJinDuTree> proplemList(JiZhuanJinDuSearchObj searchObj) {
        List<String> groupField = searchObj.getGroupField();
        if (ZStringUtils.isEmpty(groupField)) throw new ServiceErrorException("分组字段不能为空");
        List<Field> fields = new ArrayList<>(groupField.size());
        try {
            for (String fieldName : groupField) {
                Field field = JiZhuanJinDuTree.class.getDeclaredField(fieldName);
                field.setAccessible(true);
                fields.add(field);
            }
            searchObj.setCompanyId(UserIdThread.get().getCompanyId());
            List<JiZhuanJinDuTree> list = sdStyleMapper.queryTaskProblemSolveTree(searchObj);
            List<JiZhuanJinDuTree> result = getTrees(list, groupField, fields);
            return result;

        } catch (Exception e) {
            throw new ServiceErrorException("无效的分组字段");
        }
    }

    @Override
    @AutoPageAop
    public ResponseInfo queryProblemHeadList(JiZhuanJinDuSearchObj searchObj) {
        Map<String, Object> map = new HashMap<>();
        searchObj.setCompanyId(UserIdThread.get().getCompanyId());
        List<TaskProblemSolve> list = sdStyleMapper.queryTaskProblemSolve(searchObj);
        map.put("total", new PageInfo(list).getTotal());
        map.put("list", list);
        return ResponseInfo.ok(map);
    }

    @Override
    @AutoPageAop
    public ResponseInfo selectByExample(TrailTaskProcess trailTaskProcess) {
        Map<String, Object> map = new HashMap<>();
        Calendar cale;
        cale = Calendar.getInstance();
        cale.add(Calendar.MONTH, 0);
        cale.set(Calendar.DAY_OF_MONTH, 1);
        Date start = cale.getTime();
        cale = Calendar.getInstance();
        cale.add(Calendar.MONTH, 1);
        cale.set(Calendar.DAY_OF_MONTH, 0);
        Date end = cale.getTime();
        trailTaskProcess.setBeginDate(start);
        trailTaskProcess.setEndDate(end);
        List<TrailTaskProcess> list = sdStyleMapper.selectByExample1(trailTaskProcess);
        map.put("total", new PageInfo(list).getTotal());
        map.put("list", list);
        return ResponseInfo.ok(map);
    }

    @Override
    @Transactional
    public ResponseInfo queryByQrCode(String qrCode) {
        TrailTaskProcess result = sdStyleMapper.queryByQrCode(qrCode);
        if (result == null) {
            throw new ServiceErrorException("无效二维码!！");
        }
        if (result.getPlanQty() == null || result.getPlanQty().intValue() == 0) {
            throw new ServiceErrorException("还未设置产量!！");
        }
        if ("1".equals(result.getFinishFlag())) {
            throw new ServiceErrorException("该单已采集完成!！");
        }
        return ResponseInfo.ok(result);
    }

    @Autowired
    SdUserMapper sdUserMapper;

    @Override
    @Transactional
    @RedisLock(key = "trailTaskProcess")
    public ResponseInfo addTrailTaskProcess(TrailTaskProcess trailTaskProcess) {
        String name = UserIdThread.get().getLoginName();
        int seqNo = sdStyleMapper.queryMaxSeqNo(trailTaskProcess);
        trailTaskProcess.setSeqNo(Integer.valueOf(seqNo + 1));
        trailTaskProcess.setSysUser(name);
        Integer id = sdUserMapper.getUserIdByName(UserIdThread.get().getUserName());
        List<SysPost> list = sdStyleMapper.selectUserPostsByUserId(id);
        if (list == null || list.isEmpty()) {
            throw new ServiceErrorException("请先设置用户的工序岗位!！");
        }
        if (trailTaskProcess.getFinishQty() == 0 || trailTaskProcess.getFinishQty() == null)
            throw new ServiceErrorException("该工序已采集");
        int finishNumAll = sdStyleMapper.queryAlreadyFinishNum(trailTaskProcess);
        Integer finishQty = trailTaskProcess.getFinishQty() == null ? 0 : trailTaskProcess.getFinishQty();
        Integer planQty = trailTaskProcess.getPlanQty() == null ? 0 : trailTaskProcess.getPlanQty();
        if (finishNumAll + finishQty > planQty)
            throw new ServiceErrorException("采集数超出总数!！");
        if (finishNumAll + finishQty == planQty) {
            trailTaskProcess.setFinishFlag("1");
            sdStyleMapper.updateFinishFlag(trailTaskProcess);
        }
        trailTaskProcess.setProcessName(((SysPost) list.get(0)).getPostName());
        trailTaskProcess.setProcessCode(((SysPost) list.get(0)).getPostCode());
        sdStyleMapper.insertTrialTask(trailTaskProcess);
        return ResponseInfo.ok();
    }

    @Override
    @Transactional
    public ResponseInfo deleteDataByRowId(TrailTaskProcess trailTaskProcess) {
        sdStyleMapper.deleteDataByRowId(trailTaskProcess);
        return ResponseInfo.ok();
    }

    @Override
    @Transactional
    public ResponseInfo deleteAllProcess(PcStyleCraftRequest rep) {
        rep.setCompanyId(UserIdThread.get().getCompanyId());
        sdStyleMapper.deleteAllProcessHead(rep);
        sdStyleMapper.deleteAllProcessDetail(rep);
        sdStyleMapper.deleteDiff(rep);
        return ResponseInfo.ok("删除成功");
    }

    @Override
    @Transactional
    public ResponseInfo updatePcStyleProcess(List<StyleProductionProcess> list) {
        if (ZStringUtils.isEmpty(list)) throw new  ServiceErrorException("不能保存空值");
        for (StyleProductionProcess process : list) {
            String flag = sdStyleMapper.getFlagByProcessHead(process.getStyle(),process.getColor(),UserIdThread.get().getCompanyId());
            if ("Y".equals(flag)) throw new ServiceErrorException("该型体检核");
            boolean b = ZStringUtils.isProcessCf(process);
            if (b) throw new ServiceErrorException("存在重复工艺");
            if (process.getCutSeq() != null) {
                switch (process.getCutSeq()) {
                    case "一裁":
                    case "CẮT 1":
                        process.setCutSeq("1");
                        break;
                    case "二裁":
                    case "CẮT 2":
                        process.setCutSeq("2");
                        break;
                    case "三裁":
                    case "CẮT 3":
                        process.setCutSeq("3");
                        break;
                    case "四裁":
                    case "CẮT 4":
                        process.setCutSeq("4");
                        break;
                    default:
                        process.setCutSeq("");
                        break;
                }
            }
            if (process.getStkFlag() != null) {
                switch (process.getStkFlag()) {
                    case "冲裁配套仓":
                    case "KHO PHỐI ĐÔI CẮT CHẶT":
                        process.setStkFlag("1");
                        break;
                    case "面底配套仓":
                    case "KHO PHỐI ĐÔI MẶT ĐẾ":
                        process.setStkFlag("2");
                        break;
                    default:
                        process.setStkFlag("");
                        break;
                }
            }
            sdStyleMapper.updateStyleProcess(process, process.getStyle(), process.getColor());
            sdStyleMapper.insertIntoLogs(process, "UPDATE", UserIdThread.get());
        }
        return ResponseInfo.ok("修改成功");
    }

    @Override
    public ResponseInfo optionTaskPrintFlag(List<TrailTaskHead> request) {
        sdStyleMapper.updatePrintFlag(request);
        return ResponseInfo.ok();
    }

    @NotNull
    private List<JiZhuanJinDuTree> getTrees(List<JiZhuanJinDuTree> list, List<String> groupField, List<Field> fields) throws Exception {
        List<JiZhuanJinDuTree> result = new ArrayList<>();
        Map<String, JiZhuanJinDuTree> map = new HashMap<>();
        for (JiZhuanJinDuTree record : list) {
            JiZhuanJinDuTree prefixRecord = null;
            for (int i = 0; i < groupField.size(); i++) {
                prefixRecord = setNode(record, fields.get(i),
                        ZStringUtils.isNull(prefixRecord) ? "" : prefixRecord.getPrefix(), map,
                        ZStringUtils.isNull(prefixRecord) ? result : prefixRecord.getChildren(),
                        (i + 1 == groupField.size()), groupField.get(i));
            }
        }
        return result;
    }


    private JiZhuanJinDuTree setNode(JiZhuanJinDuTree record, Field field, String prefix, Map<String, JiZhuanJinDuTree> map, List<JiZhuanJinDuTree> result, boolean leaf, String type) throws Exception {
        String title = (String) field.get(record);
        prefix = ZStringUtils.format("{}-{}", new Object[]{prefix, title});
        JiZhuanJinDuTree treeRecord = map.get(prefix);
        if (ZStringUtils.isNull(treeRecord)) {
            treeRecord = new JiZhuanJinDuTree();
            treeRecord.setTitle(title);
            treeRecord.setLeaf(leaf);
            treeRecord.setPrefix(prefix);
            treeRecord.setType(type);
            map.put(prefix, treeRecord);
            result.add(treeRecord);
        }
        treeRecord.setCountNum(treeRecord.getCountNum() + record.getCountNum());
        treeRecord.setOrderQty(treeRecord.getOrderQty() + record.getOrderQty());
        return treeRecord;
    }

}
